package keye.document_manage;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.Enumeration;

import javax.swing.Icon;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.UIManager;
import javax.swing.plaf.ColorUIResource;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeCellRenderer;
import javax.swing.tree.TreePath;
import javax.swing.tree.TreeSelectionModel;

public class TreeExample extends JFrame {
	private static final long serialVersionUID = 1L;
	JTree tree;
	public TreeExample() {
		super("CheckNode2 TreeExample");
		String[] strs = { "我的联系人", 
				"开发部", 
				"职能部", 
				"张三", 
				"李四",
				"王五",
				"陈六",
				"肖七",
				"刘八"}; 

		CheckNode2[] nodes = new CheckNode2[strs.length];
		for (int i = 0; i < strs.length; i++) {
			nodes[i] = new CheckNode2(strs[i]);
		}
		nodes[0].add(nodes[1]);
		nodes[0].add(nodes[2]);
		nodes[1].add(nodes[3]);
		nodes[1].add(nodes[4]);
		nodes[1].add(nodes[5]);
		nodes[2].add(nodes[6]);
		nodes[2].add(nodes[7]);
		nodes[2].add(nodes[8]);
		tree = new JTree(nodes[0]);
		tree.setCellRenderer(new CheckRenderer());
		tree.getSelectionModel().setSelectionMode(
				TreeSelectionModel.SINGLE_TREE_SELECTION);
		tree.addMouseListener(new NodeSelectionListener(tree));
		JScrollPane sp = new JScrollPane(tree);
		JPanel panel = new JPanel(new BorderLayout());
		getContentPane().add(sp, BorderLayout.CENTER);
		getContentPane().add(panel, BorderLayout.EAST);
	}

	class NodeSelectionListener extends MouseAdapter {
		JTree tree;
		NodeSelectionListener(JTree tree) {
			this.tree = tree;
		}

		@SuppressWarnings("rawtypes")
		public void mouseClicked(MouseEvent e) {
			//得到被选的节点
			int x = e.getX();
			int y = e.getY();
			int row = tree.getRowForLocation(x, y);
			TreePath path = tree.getPathForRow(row);
			//判断是否单击了节点
			if (path != null) {
				//取得被单击的节点
				CheckNode2 node = (CheckNode2) path.getLastPathComponent();
				boolean isSelected = !(node.isSelected());
				//设置被单击的节点CheckBox,使其状态与原来状态相反
				node.setSelected(isSelected);
				//如果节点是被选中,则展开子节点
				if (isSelected) {
					tree.expandPath(path);
//					tree.collapsePath(path);
				}
				//如果被选节点不是叶节点,将其所有子节点设置为CheckBox状态设成与其相同的状态
				if(!node.isLeaf()){
					node.getNextNode();
					Enumeration enu= node.children();
					while (enu.hasMoreElements()) {
						CheckNode2 n = (CheckNode2) enu.nextElement();
						n.setSelected(node.isSelected());
						if(!n.isLeaf()){
							Enumeration enuc= n.children();
							while (enuc.hasMoreElements()) {
								CheckNode2 c = (CheckNode2) enuc.nextElement();
								c.setSelected(node.isSelected());
							}
						}
					}
				}
				//刷新树(这步是必须的,否则将看不到上面所有设置的效果);
				((DefaultTreeModel) tree.getModel()).nodeChanged(node); 
				tree.revalidate();
				tree.repaint();	
			}
		}
	}

	public static void main(String args[]) {
		TreeExample frame = new TreeExample();
		frame.addWindowListener(new WindowAdapter() {
			public void windowClosing(WindowEvent e) {
				System.exit(0);
			}
		});
		frame.setSize(300, 200);
		frame.setVisible(true);
	}
}

@SuppressWarnings("serial")
class CheckRenderer extends JPanel implements TreeCellRenderer {
	//树的节点JPanel编辑,每个节点都是一个JPanel,JPanel中有一个JCheckBox和一个JLabel
	//TreeCellRenderer从DefaultMutableTreeNode(即CheckNode2)中取得数据设置节点
	//TreeCellRenderer主要设置Tree的外观,
	protected JCheckBox check;
	protected TreeLabel label;
	public CheckRenderer() {
		setLayout(null);
		add(check = new JCheckBox());
		add(label = new TreeLabel());
		check.setBackground(UIManager.getColor("Tree.textBackground"));
		label.setForeground(UIManager.getColor("Tree.textForeground"));
	}
	public Component getTreeCellRendererComponent(JTree tree, Object value,
			boolean isSelected, boolean expanded, boolean leaf, int row,
			boolean hasFocus) {
		String stringValue = tree.convertValueToText(value, isSelected,
				expanded, leaf, row, hasFocus);
		setEnabled(tree.isEnabled());
		check.setSelected(((CheckNode2) value).isSelected());
		label.setFont(tree.getFont());
		label.setText(stringValue);
		label.setSelected(isSelected);
		label.setFocus(hasFocus);
		if (leaf) {
			if(((CheckNode2) value).getIcon()!=null){
				label.setIcon(((CheckNode2) value).getIcon());
			}else{
				label.setIcon(UIManager.getIcon("Tree.leafIcon"));
			}
			
		} else if (expanded) {
			label.setIcon(UIManager.getIcon("Tree.openIcon"));
		} else {
			label.setIcon(UIManager.getIcon("Tree.closedIcon"));
		}
		return this;
	}
	//获取结点大小
	public Dimension getPreferredSize() {
		Dimension d_check = check.getPreferredSize();
		Dimension d_label = label.getPreferredSize();
		return new Dimension(d_check.width + d_label.width,
				(d_check.height < d_label.height ? d_label.height
						: d_check.height));
	}
	//布局check和label
	public void doLayout() {
		Dimension d_check = check.getPreferredSize();
		Dimension d_label = label.getPreferredSize();
		int y_check = 0;
		int y_label = 0;
		if (d_check.height < d_label.height) {
			y_check = (d_label.height - d_check.height) / 2;
		} else {
			y_label = (d_check.height - d_label.height) / 2;
		}
		check.setLocation(0, y_check);
		check.setBounds(0, y_check, d_check.width, d_check.height);
		label.setLocation(d_check.width, y_label);
		label.setBounds(d_check.width, y_label, d_label.width, d_label.height);
	}
	//设置背景颜色
	public void setBackground(Color color) {
		if (color instanceof ColorUIResource)
			color = null;
		super.setBackground(color);
	}

	public class TreeLabel extends JLabel {
		boolean isSelected;
		boolean hasFocus;
		public TreeLabel() {
		}
		public void setBackground(Color color) {
			if (color instanceof ColorUIResource)
				color = null;
			super.setBackground(color);
		}

		public void paint(Graphics g) {
			String str;
			if ((str = getText()) != null) {
				if (0 < str.length()) {
					if (isSelected) {
						g.setColor(UIManager
								.getColor("Tree.selectionBackground"));
					} else {
						g.setColor(UIManager.getColor("Tree.textBackground"));
					}
					Dimension d = getPreferredSize();
					int imageOffset = 0;
					Icon currentI = getIcon();
					if (currentI != null) {
						imageOffset = currentI.getIconWidth()
								+ Math.max(0, getIconTextGap() - 1);
					}
					g.fillRect(imageOffset, 0, d.width - 1 - imageOffset,
							d.height);
					if (hasFocus) {
						g.setColor(UIManager
								.getColor("Tree.selectionBorderColor"));
						g.drawRect(imageOffset, 0, d.width - 1 - imageOffset,
								d.height - 1);
					}
				}
			}
			super.paint(g);
		}

		public Dimension getPreferredSize() {
			Dimension retDimension = super.getPreferredSize();
			if (retDimension != null) {
				retDimension = new Dimension(retDimension.width + 3,
						retDimension.height);
			}
			return retDimension;
		}

		public void setSelected(boolean isSelected) {
			this.isSelected = isSelected;
		}

		public void setFocus(boolean hasFocus) {
			this.hasFocus = hasFocus;
		}
	}
}

@SuppressWarnings("serial")
//结点数据类
class CheckNode2 extends DefaultMutableTreeNode {
	private int selectionMode = 0;
	private boolean isSelected = false;
	private Icon icon = null;
	public CheckNode2() {
		this(null);
	}
	
	public CheckNode2(Object userObject) {
		this(userObject, true, false);
	}

	public CheckNode2(Object userObject, boolean allowsChildren,
			boolean isSelected) {
		super(userObject, allowsChildren);
		this.isSelected = isSelected;
	}

	public int getSelectionMode() {
		return selectionMode;
	}

	public void setSelected(boolean isSelected) {
		this.isSelected = isSelected;
	}

	public boolean isSelected() {
		return isSelected;
	}
	
	public void setIcon(Icon icon){
		this.icon = icon;
	}
	
	public Icon getIcon(){
		return icon;
	}
}